package com.faithnmn.learnenglishbc.fragment;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.faithnmn.learnenglishbc.MainActivity;
import com.faithnmn.learnenglishbc.R;
import com.faithnmn.learnenglishbc.adapter.LessionAdapter;
import com.faithnmn.learnenglishbc.model.Transcript;
import com.faithnmn.learnenglishbc.network.Downloader;
import com.faithnmn.learnenglishbc.service.LessionsPlayer;
import com.faithnmn.learnenglishbc.util.CommonUtil;
import com.faithnmn.learnenglishbc.util.Constants;
import com.faithnmn.learnenglishbc.util.StorageUtil;
import com.faithnmn.learnenglishbc.util.TranscriptUtil;

public class LessionFragment extends Fragment {

	private String data;
	private String title;
	private String audioName;
	private LessionAdapter adapter;
	private ArrayList<Transcript> transcripts;
	private ListView listSeris;
	private ProgressDialog loading;
	public LessionFragment(){};
	private long currentPostion;
	private int foundIndex;
	private Handler handle = new Handler();
	private TextView currentTime,totalTime,playPauseButton;
	private SeekBar progressAudio;
	private int currentSeriIndex,currentLessionIndex;
	private WaitAudioReady waitForAudioReceiver = new WaitAudioReady();
	private DownloadProgress downloadProgressReceiver = new DownloadProgress();
	private NewDataUpdateReceiver newDataUpdateReceiver = new NewDataUpdateReceiver();
	private LayoutInflater inflater;
	private boolean isLanscape = false;
	private int offset = 100;
	
	public static LessionFragment getInstance(String title,String data,String audioName,int currentSeriIndex,int currentLessionIndex){
		LessionFragment fragment = new LessionFragment();
		Bundle bundle = new Bundle();
		bundle.putString("title", title);
		bundle.putString("data", data);
		bundle.putString("audioName", audioName);
		bundle.putInt("currentSeriIndex", currentSeriIndex);
		bundle.putInt("currentLessionIndex", currentLessionIndex);
		fragment.setArguments(bundle);
		return fragment;
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		isLanscape = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE;
		if(isLanscape){
			offset = getResources().getDisplayMetrics().widthPixels / 2;
		}else{
			offset = getResources().getDisplayMetrics().heightPixels / 2;
		}
		offset -= (int)(100f * getResources().getDisplayMetrics().scaledDensity);
		Log.e("OnConfigChange","onConfigChange, is Lanscape:"+isLanscape+", offset:"+offset);
		super.onConfigurationChanged(newConfig);
	}
	
	private Runnable synCurrentPosition = new Runnable() {
		
		@SuppressLint("NewApi")
		@Override
		public void run() {
			int foundIndex = 0;
			if(LessionsPlayer.getMediaplayer() != null){
				currentPostion = LessionsPlayer.getMediaplayer().getCurrentPosition();
				for(int i=0;i<transcripts.size();i++){
					if(transcripts.get(i).startMilisecond < currentPostion){
						foundIndex = i;
					}else{
						break;
					}
				}
				Log.e("LessionFragment", "found index:"+foundIndex+" at :"+transcripts.get(foundIndex).startMilisecond);
				currentTime.setText(CommonUtil.getDurationString(LessionsPlayer.getMediaplayer().getCurrentPosition()));
				progressAudio.setProgress(LessionsPlayer.getMediaplayer().getCurrentPosition());
				if(foundIndex != LessionFragment.this.foundIndex){
					adapter.setCurrentPlayingIndex(foundIndex);
					adapter.notifyDataSetChanged();
					LessionFragment.this.foundIndex = foundIndex;
					if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
						listSeris.smoothScrollToPositionFromTop(foundIndex, offset, 1000);
					}else{
						listSeris.smoothScrollToPosition(LessionFragment.this.foundIndex);
					}
				}
				handle.postDelayed(this, 1000);
			}
		}
	};
	
	
	
	@Override
	public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View lessionLayout = inflater.inflate(R.layout.fragment_lession_detail, null);
		this.inflater = inflater;
		isLanscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
		if(isLanscape){
			offset = getResources().getDisplayMetrics().widthPixels / 2;
		}else{
			offset = getResources().getDisplayMetrics().heightPixels / 2;
		}
		offset -= (int)(100f * getResources().getDisplayMetrics().scaledDensity);
		Log.e("Offset","Offset:"+offset);
		data = getArguments().getString("data");
		title = getArguments().getString("title");
		currentSeriIndex = getArguments().getInt("currentSeriIndex");
		currentLessionIndex = getArguments().getInt("currentLessionIndex");
		audioName = getArguments().getString("audioName");
		listSeris = (ListView) lessionLayout.findViewById(R.id.seri_list);
		currentTime = (TextView)lessionLayout.findViewById(R.id.currentTime);
		totalTime = (TextView)lessionLayout.findViewById(R.id.totalTime);
		playPauseButton = (TextView)lessionLayout.findViewById(R.id.playPauseButton);
		progressAudio = (SeekBar)lessionLayout.findViewById(R.id.progressAudio);
		ImageView playMode = (ImageView)lessionLayout.findViewById(R.id.playMode);
		if(LessionsPlayer.getPlaymodeAll()){
			playMode.setImageResource(R.drawable.play_all);
		}else{
			playMode.setImageResource(R.drawable.play_one);
		}
		playMode.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				LessionsPlayer.savePlaymode(!LessionsPlayer.getPlaymodeAll());
				if(LessionsPlayer.getPlaymodeAll()){
					((ImageView)v).setImageResource(R.drawable.play_all);
					Toast.makeText(getActivity(), "Nghe t\u1EA5t c\u1EA3 c\u00E1c b\u00E0i!", Toast.LENGTH_SHORT).show();
				}else{
					((ImageView)v).setImageResource(R.drawable.play_one);
					Toast.makeText(getActivity(), "Ch\u1EC9 nghe b\u00E0i hi\u1EC7n t\u1EA1i", Toast.LENGTH_SHORT).show();
				}
			}
		});
		progressAudio.setEnabled(false);
		
		initMainData();
		
		loading = new ProgressDialog(getActivity());
		loading.setMessage("Loading..");
		loading.setCancelable(true);
//		loading.show();
		if(LessionsPlayer.getMediaplayer() != null && LessionsPlayer.isPlayingMe(currentSeriIndex, currentLessionIndex)){
			loading.dismiss();
			initPlayerView(LessionsPlayer.getMediaplayer());
		}else{
			prepareLoadAudio();
		}
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constants.NOTIFY_AUDIO_READY_ACTION);
		filter.addAction(Constants.PLAYER_PLAY_PAUSE_ACTION);
		filter.addAction(Constants.PLAYER_CLOSE_ACTION);
		getActivity().registerReceiver(waitForAudioReceiver, filter);
		IntentFilter downloadFilter = new IntentFilter(Constants.DOWNLOAD_PROGRESS);
		LocalBroadcastManager.getInstance(getActivity()).registerReceiver(downloadProgressReceiver, downloadFilter);
		IntentFilter newDataFilter = new IntentFilter(Constants.NOTIFY_NEW_DATA_LESSION);
		LocalBroadcastManager.getInstance(getActivity()).registerReceiver(newDataUpdateReceiver, newDataFilter);
		return lessionLayout;
	}


	private void initMainData() {
		if(inflater == null){
			return;
		}
		((MainActivity)getActivity()).getChangeActionbarTitle().changeActionBarTitle(title);
		JSONObject jsonData = null;
		try {
			jsonData = new JSONObject(data);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		transcripts = TranscriptUtil.getTranscripts(jsonData);
		adapter = new LessionAdapter(getActivity(),inflater, android.R.layout.simple_list_item_1, transcripts);
		listSeris.setAdapter(adapter);
	}


	private void prepareLoadAudio() {
		if(loading != null && !loading.isShowing()){
			loading.show();
		}
		if(!StorageUtil.checkAudioAvailable(audioName)){
			loading.setMessage("Load audio from network.. Please wait");
		}else{
			loading.setMessage("Load audio from local..");
		}
		Intent playLession = new Intent(getActivity(), LessionsPlayer.class);
		playLession.setAction(Constants.PLAY_LESSION_ACTION);
		playLession.putExtra("audioName", audioName);
		playLession.putExtra("title",title);
		playLession.putExtra("currentSeriIndex", currentSeriIndex);
		playLession.putExtra("currentLessionIndex", currentLessionIndex);
		getActivity().startService(playLession);
	}
	
	
	@Override
	public void onDestroyView() {
		handle.removeCallbacks(synCurrentPosition);
		try {
			getActivity().unregisterReceiver(waitForAudioReceiver);
			LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(downloadProgressReceiver);
			LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(newDataUpdateReceiver);
		} catch (Exception e) {
		}
		((MainActivity)getActivity()).getChangeActionbarTitle().changeActionBarTitle("Learn English BC");
		super.onDestroyView();
	}
	
	private void initPlayerView(MediaPlayer mp) {
		if(mp == null){
			return;
		}
		if(mp.isPlaying()){
			playPauseButton.setText("Playing");
		}else{
			playPauseButton.setText("Paused");
		}
		playPauseButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(LessionsPlayer.getMediaplayer()!= null){
					if(LessionsPlayer.getMediaplayer().isPlaying()){
						playPauseButton.setText("Paused");
						handle.removeCallbacks(synCurrentPosition);
						Intent playPauseAction = new Intent(Constants.PLAYER_PLAY_PAUSE_ACTION);
						getActivity().sendBroadcast(playPauseAction);
					}else{
						playPauseButton.setText("Playing");
						handle.postDelayed(synCurrentPosition, 1000);
						Intent playPauseAction = new Intent(Constants.PLAYER_PLAY_PAUSE_ACTION);
						getActivity().sendBroadcast(playPauseAction);
					}
				}else{
					Intent playLession = new Intent(getActivity(), LessionsPlayer.class);
					playLession.setAction(Constants.PLAY_LESSION_ACTION);
					playLession.putExtra("audioName", audioName);
					playLession.putExtra("title",title);
					playLession.putExtra("currentSeriIndex", currentSeriIndex);
					playLession.putExtra("currentLessionIndex", currentLessionIndex);
					getActivity().startService(playLession);
					handle.removeCallbacks(synCurrentPosition);
					playPauseButton.setText("Initing..");
					handle.postDelayed(synCurrentPosition, 1000);
				}
			}
		});
		progressAudio.setEnabled(true);
		progressAudio.setMax(mp.getDuration());
		totalTime.setText(CommonUtil.getDurationString(mp.getDuration()));
		progressAudio.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
				if(LessionsPlayer.getMediaplayer() != null && fromUser){
					LessionsPlayer.getMediaplayer().seekTo(progress);
		        }
			}
		});
		handle.postDelayed(synCurrentPosition, 100);
	}

	public class DownloadProgress extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent != null && intent.getAction()!= null && intent.getAction().equals(Constants.DOWNLOAD_PROGRESS)){
				int progress = intent.getIntExtra("progress", 0);
				if(loading != null){
					loading.setMessage("\u0110ang l\u01B0u \u00E2m thanh : "+progress +"%");
					if(progress != 100){
						loading.show();
					}
				}
			}
		}
		
	}
	
	public class WaitAudioReady extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent != null && intent.getAction()!= null && intent.getAction().equals(Constants.NOTIFY_AUDIO_READY_ACTION)){
				boolean ready = intent.getBooleanExtra("done", false);
				boolean immediate = intent.getBooleanExtra("immediate", false);
				if(ready){
					handle.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							initPlayerView(LessionsPlayer.getMediaplayer());
							if(loading != null && loading.isShowing()){
								loading.dismiss();
							}
						}
					}, immediate?10:1500);
				}else{
				}
			}else if(intent != null && intent.getAction()!= null && intent.getAction().equals(Constants.PLAYER_PLAY_PAUSE_ACTION)){
				if(LessionsPlayer.getMediaplayer() != null){
					new Handler().postDelayed(new Runnable() {
						
						@Override
						public void run() {
							if(LessionsPlayer.getMediaplayer().isPlaying()){
								playPauseButton.setText("Playing");
								handle.removeCallbacks(synCurrentPosition);
								handle.postDelayed(synCurrentPosition, 1000);
							}else{
								playPauseButton.setText("Paused");
								handle.removeCallbacks(synCurrentPosition);
							}
						}
					}, 800);
				}
			}else if(intent != null && intent.getAction()!= null && intent.getAction().equals(Constants.PLAYER_CLOSE_ACTION)){
				playPauseButton.setText("Stopped");
				foundIndex = 0;
				listSeris.smoothScrollToPosition(0);
				currentTime.setText("00:00");
				progressAudio.setProgress(0);
			}
		}
		
	}
	
	public class NewDataUpdateReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent != null && intent.getAction()!= null && intent.getAction().equals(Constants.NOTIFY_NEW_DATA_LESSION)){
				String audioReadyName = intent.getStringExtra("audioName");
				String lessionTitle = intent.getStringExtra("lessionTitle");
				String data = intent.getStringExtra("data");
				int currentSeri = intent.getIntExtra("currentSeriIndex", 0);
				int currentLession = intent.getIntExtra("currentLessionIndex", 0);
				audioName = audioReadyName;
				title = lessionTitle;
				currentSeriIndex = currentSeri;
				currentLessionIndex = currentLession;
				foundIndex = 0;
				LessionFragment.this.data = data;
				progressAudio.setMax(LessionsPlayer.getMediaplayer().getDuration());
				totalTime.setText(CommonUtil.getDurationString(LessionsPlayer.getMediaplayer().getDuration()));
				initMainData();
			}
		}
		
	}

}
